import { uid, pick, compose, on, map } from '../common/utils';
import { pickIfExist } from '../common/ts_utils';
import db from './db';

const model = {
    table: db.testSuites,
    list: () => {
        return db.testSuites.toArray();
    },
    insert: (data) => {
        if (!data.name) {
            throw new Error('Model TestSuite - insert: 缺少name');
        }

        if (!Array.isArray(data.cases)) {
            throw new Error('Model TestSuite - insert: cases 应为数组');
        }

        data.updateTime = new Date() * 1;
        data.id = uid();
        return db.testSuites.add(data);
    },
    bulkInsert: (tcs) => {
        const list = tcs.map((data) => {
            if (!data.name) {
                throw new Error('Model TestSuite - insert: 缺少name');
            }

            if (!Array.isArray(data.cases)) {
                throw new Error('Model TestSuite - insert: cases应为数组');
            }

            data.updateTime = new Date() * 1;
            data.id = uid();

            return data;
        });

        return db.testSuites.bulkAdd(list);
    },
    update: (id, data) => {
        return db.testSuites.update(id, data);
    },
    remove: (id) => {
        return db.testSuites.delete(id);
    },
};

export default model;

export function normalizeTestSuite(ts) {
    return pickIfExist(['id', 'name', 'cases'], ts);
}
